import axios from 'axios';
import { ElMessage } from 'element-plus'

const ERROR_MESSAGES = {
  400: '错误的请求',
  401: '未授权，请重新登录',
  403: '拒绝访问',
  404: '请求错误,未找到该资源',
  500: '服务器端出错',
  default: '未知错误',
  network: '网络异常，请稍后再试'
};

class HttpRequest {
  constructor(baseURL = '') {
    this.instance = axios.create({
      baseURL,
      timeout: 15000,
    });
    this.initInterceptors();
  }

  initInterceptors() {
    this.instance.interceptors.request.use(
      config => config,
      error => Promise.reject(error)
    );

    this.instance.interceptors.response.use(
      response => response.data,
      this.handleError
    );
  }

  handleError = (error) => {
    let message;
    if (error.response) {
      const { status } = error.response;
      message = ERROR_MESSAGES[status] || ERROR_MESSAGES.default;
      // 可以在这里处理特定状态码的逻辑，比如 401 时登出
      if (status === 401) {
        // logout();
      }
      if(status == 400){
        message = error.response.data.msg;
      }
    } else if (error.request) {
      message = ERROR_MESSAGES.network;
    } else {
      message = error.message;
    }

    ElMessage({ message, type: 'error', duration: 5000 });
    return Promise.reject(error);
  }

  request(method, url, data = {}, config = {}) {
    const options = {
      method,
      url,
      ...config,
      ...(method === 'get' ? { params: data } : { data }),
    };
    return this.instance.request(options);
  }

  get(url, params, config) { return this.request('get', url, params, config); }
  post(url, data, config) { return this.request('post', url, data, config); }
  put(url, data, config) { return this.request('put', url, data, config); }
  delete(url, data, config) { return this.request('delete', url, data, config); }
}

const request = new HttpRequest(import.meta.env.VITE_BASE_API);

export default request;

